package org.example.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.system.common.model.Option;
import org.example.system.common.result.Result;
import org.example.system.model.dto.FileInfo;

import org.example.system.model.entity.BizLocation;
import org.example.system.model.entity.BizModel;
import org.example.system.model.entity.Vehicle;
import org.example.system.model.form.VehicleFrom;
import org.example.system.model.query.VehicleDetailQuery;
import org.example.system.model.query.VehiclePageQuery;

import org.example.system.model.query.VehicleQuery;
import org.example.system.model.vo.PageVo;
import org.example.system.model.vo.VehicleListVO;
import org.example.system.model.vo.VehicleVO;

import org.example.system.service.BizLocationService;
import org.example.system.service.BizModelService;
import org.example.system.service.OssService;
import org.example.system.service.VehicleService;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Tag(name = "12.车辆管理")
@RestController
@RequestMapping("/api/v1/vehicle")
@RequiredArgsConstructor
@Slf4j
public class VehicleController {
    private final VehicleService vehicleService;

    @Resource(name = "aliYunOssService")
    private OssService ossService;

    @Resource
    private ModelMapper modelMapper;

    private final BizModelService modelService;

    private final BizLocationService bizLocationService;



    @Operation(summary="根据id逻辑删除车辆")
    @GetMapping("/delete/{id}")
    public Result delete(@PathVariable(value = "id") Long id) {
        vehicleService.removeById(id);
        return Result.success("删除成功");

    }


    @Operation(summary="根据id恢复删除的车辆")
    @GetMapping("/recover/{id}")
    public Result recover(@PathVariable(value = "id") Integer id) {
        vehicleService.recoveId(id);
        return Result.success("恢复成功");
    }

    @Operation(summary="根据id物理删除车辆")
    @DeleteMapping("/remove/{id}")
    public Result remove(@PathVariable(value = "id") Integer id) {
        vehicleService.removeId(id);
        return Result.success("删除成功");
    }


    @Operation(summary="增加车辆")
    @PostMapping("/add")
    public Result add(@RequestBody VehicleFrom vehicleFrom) {
        Vehicle vehicle = modelMapper.map(vehicleFrom, Vehicle.class);
        LambdaQueryWrapper<Vehicle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Vehicle::getLicensePlate, vehicle.getLicensePlate());
        if (vehicleService.getOne(queryWrapper) != null) {
            return Result.failed("车牌号已存在");
        }
        FileInfo insurance = ossService.uploadFile(vehicleFrom.getInsuranceFile());
        vehicle.setInsurancePath(insurance.getUrl());
        FileInfo drive = ossService.uploadFile(vehicleFrom.getDriveFile());
        vehicle.setPhotoPath(drive.getUrl());
        vehicleService.save(vehicle);
        return Result.success("添加成功");
    }

    @Operation(summary="根据id查询车辆")
    @GetMapping("/get/{id}")
    public Result get(@PathVariable(value = "id") Long id) {
        Vehicle vehicle= vehicleService.getById(id);
        if(vehicle==null) {
            return Result.failed("车辆不存在");
        }
        return Result.success(vehicle);
    }


    @Operation(summary="修改车辆")
    @PostMapping("/update")
    public Result update(@RequestBody Vehicle vehicle) {
        vehicleService.updateById(vehicle);
        return Result.success("更新成功");
    }

    @Operation(summary="车辆列表")
    @GetMapping("/list")
    public Result list() {
        List<Vehicle> list = vehicleService.list();
        return Result.success(list);
    }

    @Operation(summary = "多条件分页查询车辆列表(弃用)")
    @PostMapping("/search1")
    public Result queryPage(@RequestBody VehiclePageQuery vehicleQuery) {
        PageVo<VehicleVO> pageVo = vehicleService.findVoPage(vehicleQuery);
        return Result.success(pageVo);
    }
    @Operation(summary = "多条件分页查询车辆列表")
    @PostMapping("/search")
    public Result queryVehicles(@RequestBody VehiclePageQuery query) {
        IPage<Vehicle> vehicleIPage = vehicleService.queryVehicles(query);
        return Result.success(vehicleIPage);
    }

    @Operation(summary = "获取所有车辆品牌")
    @GetMapping("/brand")
    public Result getBrandList(){
        QueryWrapper<Vehicle> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DISTINCT(brand)");
        List<Vehicle> list = vehicleService.list(queryWrapper);
        List<Option> optionList = list.stream().map(item -> {
            Option option = new Option();
            option.setLabel(item.getBrand());
            option.setValue(item.getBrand());
            return option;
        }).collect(Collectors.toList());
        return Result.success(optionList);
    }

    @Operation(summary = "获取所有车辆车型")
    @GetMapping("/model")
    public Result getModelList(){
        QueryWrapper<BizModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id","model_name");
        List<BizModel> list = modelService.list(queryWrapper);
        List<Option> optionList = list.stream().map(item -> {
            Option option = new Option();
            option.setLabel(item.getModelName());
            option.setValue(item.getId());
            return option;
        }).collect(Collectors.toList());
        return Result.success(optionList);
    }

    @Operation(summary = "获取所有网点列表")
    @GetMapping("/location")
    public Result getLocationList(){
        QueryWrapper<BizLocation> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id","title");
        List<BizLocation> list = bizLocationService.list(queryWrapper);
        List<Option> optionList = list.stream().map(item -> {
            Option option = new Option();
            option.setLabel(item.getTitle());
            option.setValue(item.getId());
            return option;
        }).collect(Collectors.toList());
        return Result.success(optionList);
    }


    @Operation(summary="根据车辆车牌号查询")
    @PostMapping("/searchByLicensePlate")
    public Result searchByLicensePlate(@RequestBody VehiclePageQuery vehiclePageQuery) {
        LambdaQueryWrapper<Vehicle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Vehicle::getLicensePlate, vehiclePageQuery.getLicensePlate());
        queryWrapper.orderByDesc(Vehicle::getCreateTime);
        int pageNum= vehiclePageQuery.getPageNum();
        int pageSize= vehiclePageQuery.getPageSize();
        Page<Vehicle> page = new Page<>(pageNum, pageSize);
        Page<Vehicle> vehiclePage = vehicleService.page(page, queryWrapper);
        return Result.success(vehiclePage);
    }



    @Operation(summary="根据创建时间区间查询")
    @PostMapping("/searchByCreateTime")
    public Result searchByCreateTime(
            @RequestParam(value="startTime",required = false) String startTime,
            @RequestParam(value="endTime",required = false) String endTime,
            @RequestBody VehiclePageQuery vehiclePageQuery) {
        LambdaQueryWrapper<Vehicle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.between((startTime !=null && endTime !=null),
                Vehicle::getCreateTime, startTime, endTime);
        queryWrapper.orderByDesc(Vehicle::getCreateTime);
        int pageNum= vehiclePageQuery.getPageNum();
        int pageSize= vehiclePageQuery.getPageSize();
        Page<Vehicle> page = new Page<>(pageNum, pageSize);
        vehicleService.page(page, queryWrapper);
        PageVo pageVO=new PageVo();
        pageVO.setList(page.getRecords());
        pageVO.setTotal(page.getTotal());
        return Result.success(pageVO);

    }



    @Operation(summary="按网点分页模糊查询")
    @PostMapping("/searchByLocation")
    public Result searchByLocation(@RequestParam(value="location",required = false) String location,
                                   @RequestBody VehiclePageQuery vehiclePageQuery) {
        LambdaQueryWrapper<Vehicle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(location != null, Vehicle::getLocationId, location);
        queryWrapper.orderByDesc(Vehicle::getCreateTime);
        int pageNum = vehiclePageQuery.getPageNum();
        int pageSize = vehiclePageQuery.getPageSize();
        Page<Vehicle> page = new Page<>(pageNum, pageSize);
        vehicleService.page(page, queryWrapper);
        PageVo pageVO = new PageVo();
        pageVO.setList(page.getRecords());
        pageVO.setTotal(page.getTotal());
        return Result.success(pageVO);

    }


    @PostMapping("/query")
    @Operation(summary = "多条件查询车辆信息[小程序]")
    public Result queryVehicle(@RequestBody VehicleQuery vehicleQuery) {
        // 构建车辆查询条件
        LambdaQueryWrapper<Vehicle> vehicleQueryWrapper = new LambdaQueryWrapper<>();

        // 根据门店过滤
        if (vehicleQuery.getLocationId() != null) {
            vehicleQueryWrapper.eq(Vehicle::getLocationId, vehicleQuery.getLocationId());
        }

        // 根据车型类型过滤
        if (vehicleQuery.getModelType() != null) {
            vehicleQueryWrapper.in(Vehicle::getModelId, modelService.lambdaQuery()
                    .eq(BizModel::getModelType, vehicleQuery.getModelType())
                    .select(BizModel::getId).list().stream().map(BizModel::getId).toList());
        }

        // 根据品牌过滤
        if (vehicleQuery.getBrand() != null) {
            vehicleQueryWrapper.eq(Vehicle::getBrand, vehicleQuery.getBrand());
        }

        // 根据车型配置（燃料类型）过滤
        if (vehicleQuery.getFuelType() != null) {
            vehicleQueryWrapper.in(Vehicle::getModelId, modelService.lambdaQuery()
                    .eq(BizModel::getFuelType, vehicleQuery.getFuelType())
                    .select(BizModel::getId).list().stream().map(BizModel::getId).toList());
        }

        // 根据座位数过滤
        if (vehicleQuery.getSeatNumber() != null) {
            vehicleQueryWrapper.in(Vehicle::getModelId, modelService.lambdaQuery()
                    .eq(BizModel::getSeatNumber, vehicleQuery.getSeatNumber())
                    .select(BizModel::getId).list().stream().map(BizModel::getId).toList());
        }

        // 根据价格区间过滤
        if (vehicleQuery.getPriceRange() != null) {
            List<Integer> modelIds = modelService.lambdaQuery()
                    .select(BizModel::getId, BizModel::getDailyRent)
                    .list().stream()
                    .filter(model -> {
                        BigDecimal dailyRent = model.getDailyRent();
                        if (dailyRent == null) {
                            return false;
                        }
                        switch (vehicleQuery.getPriceRange()) {
                            case 0:
                                return dailyRent.compareTo(new BigDecimal("0")) >= 0 && dailyRent.compareTo(new BigDecimal("200")) <= 0;
                            case 1:
                                return dailyRent.compareTo(new BigDecimal("200")) > 0 && dailyRent.compareTo(new BigDecimal("300")) <= 0;
                            case 2:
                                return dailyRent.compareTo(new BigDecimal("300")) > 0 && dailyRent.compareTo(new BigDecimal("500")) <= 0;
                            case 3:
                                return dailyRent.compareTo(new BigDecimal("500")) > 0;
                            default:
                                return false;
                        }
                    }).map(BizModel::getId).toList();
            vehicleQueryWrapper.in(Vehicle::getModelId, modelIds);
        }

        // 只需要车辆状态为零的车辆
        vehicleQueryWrapper.eq(Vehicle::getStatus, 0);

        // 查询车辆列表
        List<Vehicle> vehicles = vehicleService.list(vehicleQueryWrapper);


        // 按车辆类型统计数量
        Map<Integer, Long> vehicleTypeCountMap = vehicles.stream()
                .collect(Collectors.groupingBy(Vehicle::getModelId, Collectors.counting()));

        // 查询车辆对应的 Model 信息并映射到 VehicleVO
        List<VehicleVO> result = vehicles.stream().map(vehicle -> {
            BizModel model = modelService.getById(vehicle.getModelId());
            VehicleVO vehicleVO = new VehicleVO()
                    .setModelId(vehicle.getModelId())
                    .setModelName(model.getModelName())
                    .setSeatNumber(model.getSeatNumber())
                    .setDisplacement(model.getDisplacement())
                    .setGear(model.getGear())
                    .setFuelType(model.getFuelType())
                    .setDailyRent(model.getDailyRent())
                    .setPhotoPath(vehicle.getPhotoPath())
                    .setStock(String.valueOf(vehicleTypeCountMap.getOrDefault(vehicle.getModelId(), 0L).intValue())); // 设置车辆类型数量
            return vehicleVO;
        }).toList();



        // 转换为可变列表
        result = new ArrayList<>(result);

        // 根据价格排序
        if (vehicleQuery.getPriceSort() != null) {
            boolean isAsc = vehicleQuery.getPriceSort() == 0;
            result.sort(Comparator.comparing(VehicleVO::getDailyRent, isAsc ? Comparator.naturalOrder() : Comparator.reverseOrder()));
        }
        return Result.success(result);
    }


}
